package org.triumphxx.ruleexecutor;

import lombok.extern.slf4j.Slf4j;
import org.triumphxx.ruleelements.BaseRule;
import org.triumphxx.rule.dto.base.RuleDTO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:triumphxx
 * @Date: 2024/1/8
 * @Time: 14:17
 * @微信公众号：思考集结处
 * @网站：http://blog.triumphxx.com.cn
 * @GitHub https://github.com/triumphxx
 * @Desc: 规则执行器
 **/
@Slf4j
public class RuleExecutor {
    // 规则集合
    private Map<Integer, List<BaseRule>> hashMap = new HashMap<>();
    // 并运算 标志
    private static final int AND = 1;
    // 或运算 标志
    private static final int OR = 0;

    /**
     * 创建规则执行器
     * @return
     */
    public static RuleExecutor create() {
        return new RuleExecutor();
    }

    /**
     * 逻辑计算  and  并计算 规则准备
     * @param ruleList
     * @return
     */
    public RuleExecutor and(List<BaseRule> ruleList) {
        hashMap.put(AND, ruleList);
        return this;
    }

    /**
     * 逻辑允许 or  或计算 规则准备
     * @param ruleList
     * @return
     */
    public RuleExecutor or(List<BaseRule> ruleList) {
        hashMap.put(OR, ruleList);
        return this;
    }

    /**
     * 执行规则
     * @param dto
     * @return
     */
    public boolean execute(RuleDTO dto) {
        // 循环获取规则集合并执行规则
        for (Map.Entry<Integer, List<BaseRule>> item : hashMap.entrySet()) {
            List<BaseRule> ruleList = item.getValue();
            switch (item.getKey()) {
                case AND:
                    // 如果是 and 关系，同步执行
                    log.info("执行并的逻辑，规则数量为：{}",ruleList.size());
                    if (!and(dto, ruleList)) {
                        return false;
                    }
                    break;
                case OR:
                    // 如果是 or 关系，并行执行
                    log.info("执行或的逻辑，规则数量为：{}",ruleList.size());
                    if (!or(dto, ruleList)) {
                        return false;
                    }
                    break;
                default:
                    break;
            }
        }
        return true;
    }

    /**
     * 逻辑计算  and  并计算
     * @param dto
     * @param ruleList
     * @return
     */
    private boolean and(Object dto, List<BaseRule> ruleList) {
        for (BaseRule rule : ruleList) {
            boolean execute = rule.execute(dto);
            if (!execute) {
                // and 关系匹配失败一次，返回 false
                return false;
            }
        }
        // and 关系全部匹配成功，返回 true
        return true;
    }

    /**
     * 逻辑允许 or  或计算
     * @param dto
     * @param ruleList
     * @return
     */
    private boolean or(Object dto, List<BaseRule> ruleList) {
        for (BaseRule rule : ruleList) {
            boolean execute = rule.execute(dto);
            if (execute) {
                // or 关系匹配到一个就返回 true
                return true;
            }
        }
        // or 关系一个都匹配不到就返回 false
        return false;
    }

}
